package com.lframework.jh.push.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageInfo;
import com.lframework.jh.push.core.components.resp.PageResult;
import com.lframework.jh.push.core.constants.StringPool;
import com.lframework.jh.push.core.exceptions.impl.DefaultClientException;
import com.lframework.jh.push.core.impl.BaseMpServiceImpl;
import com.lframework.jh.push.core.utils.Assert;
import com.lframework.jh.push.core.utils.ObjectUtil;
import com.lframework.jh.push.core.utils.PageHelperUtil;
import com.lframework.jh.push.core.utils.PageResultUtil;
import com.lframework.jh.push.core.utils.StringUtil;
import com.lframework.jh.push.service.annotations.OpLog;
import com.lframework.jh.push.service.entity.Mch;
import com.lframework.jh.push.service.enums.OpLogType;
import com.lframework.jh.push.service.mappers.MchMapper;
import com.lframework.jh.push.service.service.MchService;
import com.lframework.jh.push.service.vo.mch.CreateMchVo;
import com.lframework.jh.push.service.vo.mch.MchSelectorVo;
import com.lframework.jh.push.service.vo.mch.QueryMchVo;
import com.lframework.jh.push.service.vo.mch.UpdateMchVo;
import java.io.Serializable;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service
public class MchServiceImpl extends BaseMpServiceImpl<MchMapper, Mch> implements MchService {

    @Override
    public PageResult<Mch> query(Integer pageIndex, Integer pageSize,
        QueryMchVo vo) {

        Assert.greaterThanZero(pageIndex);
        Assert.greaterThanZero(pageSize);

        PageHelperUtil.startPage(pageIndex, pageSize);
        List<Mch> datas = this.query(vo);

        return PageResultUtil.convert(new PageInfo<>(datas));
    }

    @Override
    public List<Mch> query(QueryMchVo vo) {

        return getBaseMapper().query(vo);
    }

    @Cacheable(value = Mch.CACHE_NAME, key = "#id", unless = "#result == null")
    @Override
    public Mch findById(Integer id) {

        return getBaseMapper().selectById(id);
    }

    @Override
    public PageResult<Mch> selector(Integer pageIndex, Integer pageSize,
        MchSelectorVo vo) {

        Assert.greaterThanZero(pageIndex);
        Assert.greaterThanZero(pageSize);

        PageHelperUtil.startPage(pageIndex, pageSize);
        List<Mch> datas = getBaseMapper().selector(vo);

        return PageResultUtil.convert(new PageInfo<>(datas));
    }

    @OpLog(type = OpLogType.MCH, name = "新增商户，ID：{}, 名称：{}", params = {"#_result",
        "#vo.name"}, autoSaveParams = true)
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer create(CreateMchVo vo) {

        Wrapper<Mch> checkWrapper = Wrappers.lambdaQuery(Mch.class)
            .eq(Mch::getName, vo.getName());
        if (getBaseMapper().selectCount(checkWrapper) > 0) {
            throw new DefaultClientException("名称重复，请重新输入！");
        }

        Mch data = new Mch();
        data.setName(vo.getName());
        if (StringUtil.isNotBlank(vo.getApiSecret())) {
            data.setApiSecret(vo.getApiSecret());
        }
        data.setAvailable(Boolean.TRUE);
        data.setDescription(
            StringUtil.isBlank(vo.getDescription()) ? StringPool.EMPTY_STR : vo.getDescription());

        getBaseMapper().insert(data);

        return data.getId();
    }

    @OpLog(type = OpLogType.MCH, name = "修改商户，ID：{}, 名称：{}", params = {"#vo.id",
        "#vo.name"}, autoSaveParams = true)
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void update(UpdateMchVo vo) {

        Mch data = this.findById(vo.getId());
        if (ObjectUtil.isNull(data)) {
            throw new DefaultClientException("商户不存在！");
        }

        Wrapper<Mch> checkWrapper = Wrappers.lambdaQuery(Mch.class)
            .eq(Mch::getName, vo.getName())
            .ne(Mch::getId, vo.getId());
        if (getBaseMapper().selectCount(checkWrapper) > 0) {
            throw new DefaultClientException("名称重复，请重新输入！");
        }

        LambdaUpdateWrapper<Mch> updateWrapper = Wrappers.lambdaUpdate(Mch.class)
            .set(Mch::getName, vo.getName())
            .set(Mch::getAvailable, vo.getAvailable())
            .set(StringUtil.isNotBlank(vo.getApiSecret()), Mch::getApiSecret, vo.getApiSecret())
            .set(Mch::getDescription,
                StringUtil.isBlank(vo.getDescription()) ? StringPool.EMPTY_STR
                    : vo.getDescription())
            .eq(Mch::getId, vo.getId());

        getBaseMapper().update(updateWrapper);
    }

    @CacheEvict(value = Mch.CACHE_NAME, key = "#key")
    @Override
    public void cleanCacheByKey(Serializable key) {

    }
}
